package com.ca.project.Server.Modules.RepairImg.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ca.project.COS.CosUtil;
import com.ca.project.Minio.Util.MinioUtil;
import com.ca.project.Server.Modules.RepairImg.Context.UploadRepairImgContext;
import com.ca.project.Server.Modules.RepairImg.Converter.RepairImgConverter;
import com.ca.project.Server.Modules.RepairImg.Entity.RepairImg;
import com.ca.project.Server.Modules.RepairImg.Service.RepairImgService;
import com.ca.project.Server.Modules.RepairImg.Mapper.RepairImgMapper;
import com.ca.project.Server.Modules.UserInfo.Entity.UserInfo;
import com.ca.project.Server.Modules.UserInfo.Service.UserInfoService;
import com.ca.project.core.Exception.BusinessException;
import com.ca.project.core.Util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ASUS
 * @description 针对表【repair_img】的数据库操作Service实现
 * @createDate 2025-01-03 15:15:39
 */
@Service
public class RepairImgServiceImpl extends ServiceImpl<RepairImgMapper, RepairImg> implements RepairImgService {

    @Autowired
    private CosUtil cosUtil;
    @Autowired
    private RepairImgConverter repairImgConverter;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * 删除维修订单图片
     * <p>
     * 1.先找出图片上传的key值
     * 2.删除服务器的图片
     * 3.再删除数据库
     *
     * @param list
     */
    @Override
    public void deleteImg(Object list) {
        try {
            JSONArray jsonArray = JSON.parseArray(list.toString());
            if (jsonArray == null || jsonArray.isEmpty()) {
                throw new BusinessException("图片 ID 列表为空");
            }
            List<String> imgKeys = findImgKey(jsonArray);
            if (imgKeys == null || imgKeys.isEmpty())
                throw new BusinessException("没有找到对应的key值");
            for (String imgKey : imgKeys) {
                boolean success = cosUtil.deletePublicFile(imgKey);
                if (!success)
                    throw new BusinessException("图片删除失败");
            }
            List<String> idList = jsonArray.toJavaList(String.class);
            int row = baseMapper.deleteBatchIds(idList);
            if (row <= 0)
                throw new BusinessException("图片删除失败");
        } catch (Exception e) {
            throw new BusinessException("图片删除过程出错");
        }
    }

    /**
     * 找出图片的url集合
     *
     * @param rImgList
     * @return
     */
    @Override
    public List<String> findImg(Object rImgList) {
        try {
            JSONArray jsonArray = JSON.parseArray(rImgList.toString());
            if (jsonArray == null || jsonArray.isEmpty()) {
                throw new BusinessException("图片 ID 列表为空");
            }
            List<String> imgUrl = findImgUrl(jsonArray);
            if (imgUrl == null || imgUrl.isEmpty())
                throw new BusinessException("没有找到对应的url");
            return imgUrl;
        } catch (Exception e) {
            throw new BusinessException("没有找到对应的url");
        }
    }

    /**
     * 上传图片
     *
     * @param uploadRepairImgContext
     * @return
     */
    @Override
    public String upload(UploadRepairImgContext uploadRepairImgContext) {
        doValidToken(uploadRepairImgContext);
        assembleRepairImg(uploadRepairImgContext);
        doCreate(uploadRepairImgContext);
        return uploadRepairImgContext.getEntity().getRImgUrl();
    }

    /**
     * 删除图片
     *
     * @param url
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRepairImg(String url) {
        try {
            QueryWrapper<RepairImg> wrapper = new QueryWrapper<>();
            wrapper.eq("r_img_url", url);
            RepairImg entity = getOne(wrapper);
            if (Objects.isNull(entity))
                throw new BusinessException("图片不存在");
            //boolean success = cosUtil.deletePublicFile(entity.getRImgKey());
            boolean success = minioUtil.deleteFile(entity.getRImgKey());
            if (!success)
                throw new BusinessException("服务器图片删除失败");
            int row = baseMapper.delete(wrapper);
            if (row == 0)
                throw new BusinessException("图片删除失败");
        } catch (Exception e) {
            throw new BusinessException("图片删除失败");
        }
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @param repairImg
     * @return
     */
    @Override
    public IPage<RepairImg> getPage(Integer currentPage, Integer pageSize, RepairImg repairImg) {
        LambdaQueryWrapper<RepairImg> wrapper = new LambdaQueryWrapper<>();
        IPage<RepairImg> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        return page;
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public IPage<RepairImg> getPage(Integer currentPage, Integer pageSize) {
        IPage<RepairImg> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, null);
        return page;
    }
/***********************************************private****************************************************************/
    /**
     * 找到图片key值集合
     *
     * @param jsonArray
     * @return
     */
    private List<String> findImgKey(JSONArray jsonArray) {
        List<String> idList = jsonArray.toJavaList(String.class);
        QueryWrapper<RepairImg> wrapper = new QueryWrapper<>();
        wrapper.in("r_img_id", idList);
        List<RepairImg> repairImg = baseMapper.selectList(wrapper);
        return repairImg.stream()
                .map(RepairImg::getRImgKey)
                .collect(Collectors.toList());
    }

    /**
     * 找到图片的url集合
     *
     * @param jsonArray
     * @return
     */
    private List<String> findImgUrl(JSONArray jsonArray) {
        List<String> idList = jsonArray.toJavaList(String.class);
        QueryWrapper<RepairImg> wrapper = new QueryWrapper<>();
        wrapper.in("r_img_id", idList);
        List<RepairImg> repairImg = baseMapper.selectList(wrapper);
        return repairImg.stream()
                .map(RepairImg::getRImgUrl)
                .collect(Collectors.toList());
    }

    /**
     * 校验token
     *
     * @param uploadRepairImgContext
     */
    private void doValidToken(UploadRepairImgContext uploadRepairImgContext) {
        String token = uploadRepairImgContext.getToken();
        UserInfo entity = userInfoService.find(token);
        if (Objects.isNull(entity))
            throw new BusinessException("token已失效");
        uploadRepairImgContext.setOpenid(entity.getOpenid());
    }

    /**
     * 实体转换病上传minio
     * <p>
     * 注释的内容为COS的配置
     *
     * @param uploadRepairImgContext
     */
    private void assembleRepairImg(UploadRepairImgContext uploadRepairImgContext) {
        RepairImg entity = repairImgConverter.UploadRepairImgContext2RepairImg(uploadRepairImgContext);
        MultipartFile file = uploadRepairImgContext.getFile();
        if (file.isEmpty())
            throw new BusinessException("上传文件不能为空");
        try {
            //String path = "/CA/";
            //HashMap map = cosUtil.uploadPublicFile(file, path);

            Map<String, Object> map = minioUtil.upload(file);
            //String key = (String) map.get("path");
            String key = (String) map.get("key");
            String url = (String) map.get("url");

            //if (key.startsWith("/")) {
            //    key = key.substring(1);
            //}
            final Long id = IdUtil.get();
            entity.setRImgId(id);
            entity.setRImgKey(key);
            entity.setRImgUrl(url);
            entity.setRImgOpenid(uploadRepairImgContext.getOpenid());
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            uploadRepairImgContext.setEntity(entity);
        } catch (Exception e) {
            throw new BusinessException("文件上传到Minio错误");
        }
    }

    /**
     * 创建实体
     *
     * @param uploadRepairImgContext
     */
    private void doCreate(UploadRepairImgContext uploadRepairImgContext) {
        RepairImg entity = uploadRepairImgContext.getEntity();
        if (entity == null)
            throw new BusinessException("维修图片实体不能为空");
        try {
            if (!save(entity))
                throw new BusinessException("维修图片创建失败");
        } catch (Exception e) {
            throw new BusinessException("维修图片创建失败,原因:" + e.getMessage());
        }
    }
}
